<template>
    <div class="carInfo">
        <el-form ref="AddCarRef" style="max-width: 600px" :model="carInfo" :rules="rules" label-width="auto" class="demo-ruleForm"
            :size="formSize" status-icon>
            <el-row :gutter="20">
                <el-col :span="12">
                    <el-form-item label="车名" prop="carName">
                        <el-input v-model="carInfo.carName" placeholder="请输入车名" />
                    </el-form-item>
                    <el-form-item label="车类型" prop="carType">
                        <el-select v-model="carInfo.carType" placeholder="请选择车类型">
                            <el-option value="轿车">轿车</el-option>
                            <el-option value="跑车">跑车</el-option>
                            <el-option value="皮卡车">皮卡车</el-option>
                            <el-option value="越野车">越野车</el-option>
                        </el-select>
                    </el-form-item>
                    <el-form-item label="车价格" prop="price">
                        <el-input v-model="carInfo.price" placeholder="请输入车价格" />
                    </el-form-item>
                    <el-form-item label="押金" prop="deposit">
                        <el-input v-model="carInfo.deposit" placeholder="请输入押金" />
                    </el-form-item>
                    <el-form-item label="车座数" prop="seat">
                        <el-select v-model="carInfo.seat" placeholder="请选择座位数">
                            <el-option :value="4">4座</el-option>
                            <el-option :value="5">5座</el-option>
                            <el-option :value="6">6座</el-option>
                            <el-option :value="7">7座</el-option>
                        </el-select>
                    </el-form-item>
                    <el-form-item label="动力" prop="motivity">
                        <el-input v-model="carInfo.motivity" placeholder="请输入动力(单位：T)" />
                    </el-form-item>
                    <el-form-item label="燃油型号" prop="petrol">
                        <el-select v-model="carInfo.petrol" placeholder="请选择燃油型号(油车)">
                            <el-option :value="92">92号</el-option>
                            <el-option :value="95">95号</el-option>
                            <el-option :value="98">98号</el-option>
                        </el-select>
                    </el-form-item>
                </el-col>
                <el-col :span="12">
                    <el-form-item label="车牌号" prop="carNumber">
                        <el-input v-model="carInfo.carNumber" placeholder="请输入车牌号" />
                    </el-form-item>
                    <el-form-item label="车身颜色" prop="color">
                        <el-select v-model="carInfo.color" placeholder="请选择车身颜色">
                            <el-option value="白色">白色</el-option>
                            <el-option value="灰色">灰色</el-option>
                            <el-option value="黑色">黑色</el-option>
                            <el-option value="蓝色">蓝色</el-option>
                            <el-option value="红色">红色</el-option>
                            <el-option value="紫色">紫色</el-option>
                        </el-select>
                    </el-form-item>
                    <el-form-item label="租赁价格" prop="rentPrice">
                        <el-input v-model="carInfo.rentPrice" placeholder="请输入租赁价格/天" />
                    </el-form-item>
                    <el-form-item label="动力来源" prop="electric">
                        <el-select v-model="carInfo.electric" placeholder="请选择动力来源">
                            <el-option :value="0" label="油车"></el-option>
                            <el-option :value="1" label="电车"></el-option>
                        </el-select>
                    </el-form-item>
                    <el-form-item label="车门数" prop="door">
                        <el-select v-model="carInfo.door" placeholder="请选择车门数">
                            <el-option :value="4">4门</el-option>
                            <el-option :value="6">6门</el-option>
                        </el-select>
                    </el-form-item>
                    <el-form-item label="变速" prop="auto">
                        <el-select v-model="carInfo.auto" placeholder="请选择变速方式">
                            <el-option :value="0" label="手动挡"></el-option>
                            <el-option :value="1" label="自动挡"></el-option>
                        </el-select>
                    </el-form-item>
                    <el-form-item label="驱动" prop="drive">
                        <el-select v-model="carInfo.drive" placeholder="请选择驱动方式">
                            <el-option :value="0" label="前驱"></el-option>
                            <el-option :value="1" label="后驱"></el-option>
                            <el-option :value="2" label="四驱"></el-option>
                        </el-select>
                    </el-form-item>
                </el-col>
            </el-row>
            <el-row>
                <el-col :span="24">
                    <el-form-item label="描述" prop="description">
                        <el-input type="textarea" v-model="carInfo.description" :rows="5" placeholder="车辆描述" />
                    </el-form-item>
                    <el-form-item label="图片">
                        <div class="image-container">
                            <el-upload
                                :action="baseURL + '/upload'"
                                :show-file-list="false"
                                :on-success="handleSuccess"
                                :on-change="beforeAvatarUpload"
                                class="upload-placeholder"
                            >
                            <img v-if="imageUrl" :src="imageUrl" alt="项目图片" class="uploaded-image square-image">
                            <el-icon v-else><Plus /></el-icon>
                            </el-upload>
                        </div>
                    </el-form-item>
                </el-col>
            </el-row>
            <el-row>
                <el-col :span="24">
                    <el-form-item style="padding-left:14%">
                        <el-button type="primary" @click="submitForm(AddCarRef)">保存</el-button>
                        <el-button @click="resetForm(AddCarRef)">重置</el-button>
                    </el-form-item>
                </el-col>
            </el-row>
        </el-form>
    </div>
</template>

<script lang="ts" setup>
import { reactive, ref, onMounted } from 'vue'
import type { ComponentSize, FormInstance, FormRules,} from 'element-plus'
import { addCar, getCarById, updateCar } from '@/api'
import { ElMessage } from 'element-plus'
import router from '@/router'
import { useRoute } from 'vue-router';

const baseURL = ref('http://localhost:8081/common')
const dialogImageUrl = ref('')
const dialogVisible = ref(false)
const imageUrl = ref('') // 用来存储图片URL

const handleSuccess = (response : any, uploadFile: any) => {
    // 假设API响应中包含图片URL，这里需要根据实际API返回结构调整
    imageUrl.value = baseURL.value +`/download?name=${response.data}`;
    carInfo.img = response.data
}

const beforeAvatarUpload = (file : any) => {
    const suffix = file.name.split('.')[1]
    const size = file.size / 1024 / 1024 < 10
    if(['png','jpeg','jpg'].indexOf(suffix) < 0){
        ElMessage.error('上传图片只支持 png、jpeg、jpg 格式！')
        return false
    }
    if(!size){
        ElMessage.error('上传文件大小不能超过 10MB!')
        return false
    }
    return true
}

const formSize = ref<ComponentSize>('default')
const AddCarRef = ref<FormInstance>()
let carInfo = reactive({
    id: '',
    carName: '',
    carNumber: '',
    carType: '',
    color: '',
    price: '',
    rentPrice: '',
    deposit: '',
    img: '',
    electric: '',
    seat: '',
    door: '',
    auto: '',
    motivity: '',
    drive: '',
    petrol: '',
    description: '',
    createTime: '',
    state: ''
})

const id = ref()

// 在组件挂载时初始化数据
onMounted(() => {
    const route = useRoute();
    // 获取查询参数 id存在则是编辑 反之新增
    id.value = route.query.id as string | undefined;
    if(id.value){
        // 发送请求 根据id查数据
        getCarById(id.value).then((resp: { data: any; }) => {
            let data = resp.data;
            if (data.code == '50041') {
                Object.assign(carInfo, data.data);
                imageUrl.value = baseURL.value +`/download?name=${carInfo.img}`;
            } else {
                ElMessage({
                    message: data.message,
                    type: 'error'
                });
            }
        });
    }
});

const rules = reactive<FormRules>({
    carName: [{ required: true, message: '请选择车名', trigger: 'change' }],
    carNumber: [{ required: true, message: '请输入车牌号', trigger: 'blur' }],
    carType: [{ required: true, message: '请选择车类型', trigger: 'change' }],
    color: [{ required: true, message: '请选择车身颜色', trigger: 'change' }],
    price: [{ required: true, message: '请输入车价格', trigger: 'blur' }],
    rentPrice: [{ required: true, message: '请输入租赁价格', trigger: 'blur' }],
    deposit: [{ required: true, message: '请输入押金', trigger: 'blur' }],
    electric: [{ required: true, message: '请选择动力来源', trigger: 'change' }],
    seat: [{ required: true, message: '请选择座位数', trigger: 'change' }],
    door: [{ required: true, message: '请选择车门数', trigger: 'change' }],
    auto: [{ required: true, message: '请选择变速方式', trigger: 'change' }],
    motivity: [{ required: true, message: '请输入动力', trigger: 'blur' }],
    drive: [{ required: true, message: '请选择驱动方式', trigger: 'change' }],
})

const submitForm = async (formEl: FormInstance | undefined) => {
    if (!formEl) return
    await formEl.validate((valid, fields) => {
        if (valid) {
            if(id.value){
                updateCar(carInfo).then((resp: { data: any; }) => {
                    let data = resp.data;
                    if (data.code == '50031') {
                        ElMessage({
                            message: data.message,
                            type: 'success'
                        });
                        // 发送消息给父窗口，告知要改变页面
                        window.parent.postMessage({ action: 'changePage', url: '/#/car/list' }, '*');
                    } else {
                        ElMessage({
                            message: data.message,
                            type: 'error'
                        });
                    }
                });
            }else{
                addCar(carInfo).then((resp: { data: any; }) => {
                    let data = resp.data;
                    if (data.code == '50011') {
                        ElMessage({
                            message: data.message,
                            type: 'success'
                        });
                        // 发送消息给父窗口，告知要改变页面
                        window.parent.postMessage({ action: 'changePage', url: '/#/car/list' }, '*');
                    } else {
                        ElMessage({
                            message: data.message,
                            type: 'error'
                        });
                    }
                });
            }
        } else {
            console.log('error submit!', fields)
        }
    })
}

const resetForm = (formEl: FormInstance | undefined) => {
    if (!formEl) return
    formEl.resetFields()
}

const options = Array.from({ length: 10000 }).map((_, idx) => ({
    value: `${idx + 1}`,
    label: `${idx + 1}`,
}))
</script>

<style scoped>
.carInfo {
    display: flex;
    justify-content: center;
    align-items: center;
    min-height: 100vh;
    padding: 20px;
    box-sizing: border-box;
}
/* 为上传区域添加样式 */
.upload-placeholder {
  position: relative;
  width: 200px; /* 自定义宽度，根据需求调整 */
  height: 200px; /* 自定义高度，应与宽度相同以形成正方形 */
  border: 1px solid #000; /* 黑色边框 */
  border-radius: 4px; /* 边框圆角，保持直角以维持方形外观 */
  overflow: hidden; /* 隐藏超出边界的图片部分 */
  display: flex; /* 添加Flex布局 */
  justify-content: center; /* 水平居中 */
  align-items: center; /* 垂直居中 */
}

.square-image {
    max-width: 100%;
    width: auto;
    max-height: 100%;
    height: auto;
    /* 保持图片原始宽高比 */
    object-fit: contain; /* 更改此属性为contain以保持原图比例 */
    /* 确保图片内容居中 */
    object-position: center;
    
    /* 居中显示 */
    display: block;
    margin: auto;
    position: absolute;
    top: 0;
    bottom: 0;
    left: 0;
    right: 0;
    border-radius: 0 !important; /* 确保没有圆角 */
}

/* 当没有图片时，确保加号图标居中显示（这部分可能不需要额外设置，因为已经通过Flex布局居中） */
/*.upload-placeholder .el-icon {
  // 如果之前设置导致问题，可以尝试移除此部分，仅依赖Flex布局的居中效果
}*/

/* 可选：调整加号图标的样式 */
.el-icon {
  font-size: 48px; /* 根据需要调整图标大小 */
  color: #909399; /* 图标颜色，可根据设计调整 */
}
</style>